#include <button.h>

void button_pos_handle(int btn, int x, int y, void *data)
{
    struct button_t *button = (struct button_t *)data;

    if (!button->sw && x >= button->x && x <= button->x + button->button->w &&
        y >= button->y && y <= button->y + button->button->h)
    {
        button->handle(button->data);
    }
}

struct button_t *button_create(struct sdl_t *sdl, SDL_Surface *button_pic, button_handle_t *handle, void *data)
{
    struct button_t *button = NULL;

    button = (struct button_t *)malloc(sizeof(struct button_t));
    if (button == NULL)
        return NULL;
    memset(button, 0, sizeof(struct button_t));

    button->button = button_pic;
    button->handle = handle;
    button->data = data;
    button->sdl = sdl;
    button->id = register_mouse(sdl, SDL_BUTTON_LEFT, button_pos_handle, button);

    return button;
}

struct button_t *button_create_txt(struct sdl_t *sdl, TTF_Font *font, const char *text, int color, button_handle_t *handle, void *data)
{
    SDL_Surface *op = NULL;
    SDL_Color c;
    struct button_t *button = NULL;

    c.r = (char)(color >> 16);
    c.g = (char)(color >> 8);
    c.b = (char)color;

    op = TTF_RenderUTF8_Blended(font, text, c);
    if (op == NULL)
        goto ERR1;
    button = button_create(sdl, op, handle, data);
    if (button == NULL)
        goto ERR2;
    button->free = 1;

    return button;
ERR2:
    SDL_FreeSurface(op);
ERR1:
    return NULL;
}

struct button_t *button_create_img(struct sdl_t *sdl, const char *path, button_handle_t *handle, void *data)
{
    SDL_Surface *op = NULL;
    struct button_t *button = NULL;

    op = pic_load(path);
    if (op == NULL)
        goto ERR1;
    button = button_create(sdl, op, handle, data);
    if (button == NULL)
        goto ERR2;
    button->free = 1;

    return button;
ERR2:
    SDL_FreeSurface(op);
ERR1:
    return NULL;
}


void button_show(struct button_t *button, int x, int y)
{
    SDL_Rect offset;

    offset.x = x;
    offset.y = y;

    button->x = x;
    button->y = y;

    SDL_BlitSurface(button->button, NULL, button->sdl->screen, &offset);
}

void button_set(struct button_t *button, int flag)
{
    button->sw = flag;
}

void button_destroy(struct button_t *button)
{
    if (button->free)
        SDL_FreeSurface(button->button);
    destroy_mouse(button->sdl, button->id);
    free(button);
}
